<template>
  <el-card shadow="always" class="operator">
    <div>
      <div
        style="
          margin: 20px 0px 0px 20px;
          display: flex;
          justify-content: space-between;
        ">
        <div><span>标签管理</span></div>
        <div>
          <!-- <el-input
            v-model="search"
            size="mini"
            placeholder="输入算子名称搜索"
            style="width: 200px; margin-right: 20px" />
          <el-select
            v-model="value"
            placeholder="请选择"
            size="mini"
            style="margin-right: 20px">
            <el-option label="全部" :value="1"></el-option>
            <el-option label="类别1" :value="2"></el-option>
            <el-option label="类别2" :value="3"></el-option>
          </el-select>
          <el-button type="primary" size="mini" @click="handleSearch">
            查询
          </el-button> -->
          <!-- <el-button
            type="primary"
            size="mini"
            style="margin-right: 120px"
            @click="onAdd">
            新增
          </el-button> -->
          <el-button
            type="primary"
            size="mini"
            style="margin-right: 120px"
            @click="addITag">
            新增顶级
          </el-button>
        </div>
      </div>
      <!-- <el-table
        :data="tableData"
        style="width: 100%; margin-top: 50px"
        @row-click="handleClick">
        <el-table-column prop="name" label="标签名称"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editRow(scope.row)"
              >编辑</el-button
            >
            <template>
              <el-popconfirm
                title="确定删除吗？"
                @confirm="deleteRow(scope.row)">
                <el-button
                  type="text"
                  size="small"
                  style="color: red; margin-left: 10px"
                  slot="reference"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table> -->
      <!-- 页码 -->
      <div>
        <!-- <p>标签管理</p> -->
        <!-- <el-button size="mini" @click="addITag"> 添加顶级 </el-button> -->
        <el-tree
          :data="data"
          show-checkbox
          node-key="id"
          :default-expand-all="false"
          :expand-on-click-node="false"
          :props="defaultProps">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button type="text" size="mini" @click="() => append(data)">
                添加子级
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click="() => remove(node, data)">
                <span style="color: red">删除</span>
              </el-button>
            </span>
          </span>
        </el-tree>
      </div>
      <Customdialog
        v-if="dialogOptions.visible"
        :options="dialogOptions"
        :row="currentRow"
        @onEditClose="onEditClose"
        @onAddClose="onAddClose" />
    </div>
    <!-- <el-pagination
      style="margin-top: 10px"
      layout="total,  prev, pager, next, jumper"
      :pageSize="pagination.pageSize"
      :total="pagination.total"
      :pageSizes="pagination.pageSizes"
      @current-change="pageChange"
      @size-change="sizesChange">
    </el-pagination> -->
  </el-card>
</template>

<script>
  let id = 1000;
  import Customdialog from "./components/index.vue";
  export default {
    components: {
      Customdialog,
    },
    data() {
      return {
        data: [
          {
            id: 1,
            name: "一级 1",
            children: [
              {
                id: 4,
                name: "二级 1-1",
                children: [
                  {
                    id: 9,
                    name: "三级 1-1-1",
                  },
                  {
                    id: 10,
                    name: "三级 1-1-2",
                  },
                ],
              },
            ],
          },
          {
            id: 2,
            name: "一级 2",
            children: [
              {
                id: 5,
                name: "二级 2-1",
              },
              {
                id: 6,
                name: "二级 2-2",
              },
            ],
          },
          {
            id: 3,
            name: "一级 3",
            children: [
              {
                id: 7,
                name: "二级 3-1",
              },
              {
                id: 8,
                name: "二级 3-2",
              },
            ],
          },
        ],
        defaultProps: {
          children: "children",
          label: "name",
        },
        // data: JSON.parse(JSON.stringify(data)),
        currentRow: null,
        dialogOptions: {
          title: "",
          visible: false,
          size: "small-dialog-box",
        },
        tableData: [
          {
            id: "1",
            name: "testtag1",
          },
          {
            id: "2",
            name: "testtag2",
          },
        ],

        value: 1,
        search: "",
        searchtype: null,
        // 分页参数
        pagination: {
          pageSize: 10,
          pageSizes: [10, 20],
          currentPage: 1,
          total: 50,
          layout: "total, sizes, prev, pager, next, jumper",
          onSizeChange: this.onSizeChange,
          onCurrentChange: this.onCurrentChange,
          order_field: "",
          order_type: "",
        },
      };
    },
    created() {
      this.init();
    },
    watch: {},
    methods: {
      init() {
        this.getAll();
      },
      //查询所有标签
      getAll() {
        let result = window.iTag.getAll();
        let res = JSON.parse(result);
        this.tableData = res.data;
        this.data = res.data;
        // this.pagination.total = res.data.total;

        // this.tableData.forEach((item) => {
        //   const timestamp = item.createtime;
        //   const date = new Date(timestamp);
        //   const formattedDate = date.toLocaleString().replace(/\//g, "-");
        //   item.createtime = formattedDate;
        // });
        // for (let i = 0; i < this.tableData.length; i++) {
        //   const item = this.tableData[i];
        //   const timestamp = item.createtime;
        //   const date = new Date(timestamp);
        //   const formattedDate = date.toLocaleString().replace(/\//g, "-");
        //   item.createtime = formattedDate;
        // }

        // this.pagination.pageSize = res.data.totalPage;
      },
      //搜索
      handleSearch() {
        let item = {
          name: this.search,
          type: this.value,
        };
        let itemJosn = JSON.stringify(item);
        let result = window.iOperator.findOperatorList(
          itemJosn,
          this.pagination.currentPage,
          this.pagination.pageSize
        );
        let res = JSON.parse(result);
        this.tableData = res.data.dataList;
        this.pagination.total = res.data.total;
        // if (this.search) {
        //   this.tableData = this.tableData.filter((row) => {
        //     return Object.values(row).some((text) =>
        //       text.includes(this.search)
        //     );
        //   });
        // } else {
        //   this.getAll();
        // }
      },

      handleClick(row) {
        // console.log(row);
      },
      //新增
      onAdd() {
        this.dialogOptions.title = "新增";
        this.dialogOptions.visible = true;
        this.currentRow = null;
      },
      //编辑
      editRow(row) {
        this.currentRow = row;
        // console.log("🚀 ~ editRow ~  this.currentRow :", this.currentRow);
        this.dialogOptions.title = "编辑";
        this.dialogOptions.visible = true;
      },
      // 删除
      deleteRow(row) {
        console.log("🚀 ~ deleteRow ~ scope:", row);
        var result = window.iTag.deleteTag(row.id);
        let res = JSON.parse(result);
        if (res.code == 1) {
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
        }
        this.getAll();
        // this.tableData = this.tableData.filter((item) => item !== row);
      },

      onEditClose(data) {
        console.log("🚀 ~ onEditClose ~ data:", data);
        this.currentRow = data;
        if (data) {
          const params = JSON.stringify(data);
          let result = window.iTag.updateTag(params);
          let res = JSON.parse(result);
          if (res.code == 1) {
            this.$message.success(res.msg);
          } else {
            this.$message.error(res.msg);
          }
          this.getAll();
        } else {
          this.currentRow = null;
        }
        this.dialogOptions.visible = false;
        // console.log("🚀 ~ onEditClose ~ this.currentRow:", this.currentRow);
        // if (data) {
        //   // const params = JSON.stringify(data);
        //   // console.log("🚀 ~ onEditClose ~ params:", params);
        //   // var data = iArea.editArea(params);
        //   // var res = JSON.parse(data);
        //   // // this.$message.success(res.msg);
        //   // this.$message({
        //   //   message: res.msg,
        //   //   type: "success",
        //   //   duration: 1000,
        //   // });
        //   // console.log("🚀 ~ onEditClose ~ res:", res);
        //   // // 刷新列表
        //   // this.getData();
        // } else {
        //   this.currentRow = null;
        //   this.dialogOptions.visible = false;
        // }
      },
      onAddClose(data) {
        console.log("🚀 ~ onAddClose ~ data:", data);
        // this.tableData.push(data);
        if (data) {
          const params = JSON.stringify(data);
          let result = window.iTag.updateTag(params);
          let res = JSON.parse(result);
          if (res.code == 1) {
            this.$message.success(res.msg);
          } else {
            this.$message.error(res.msg);
          }
          this.getAll();
        }
        this.dialogOptions.visible = false;
      },
      //当前页数监听
      pageChange(val) {
        console.log("🚀 ~ pageChange ~ val:", val);
        this.pagination.currentPage = val;
        this.getAll();
      },
      //每页条数监听
      sizesChange(val) {
        // console.log("🚀 ~ sizesChange ~ val:", val);
        // this.pagination.pageSize = val;
        // this.getAll();
      },
      checkInput() {
        if (isNaN(this.searchtype)) {
          this.$message.error("请输入数字");
          this.inputValue = null;
        }
      },
      //类型数字转字符
      formatType(row) {
        if (row.type === 1) {
          return "全部";
        } else if (row.type === 2) {
          return "类别1";
        } else if (row.type === 3) {
          return "类别2";
        }
      },
      //添加顶级标签
      addITag() {
        this.$prompt("", "请输入名称", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then((value) => {
            // console.log("🚀 ~ .then ~ value:", value.value);
            let item = {
              name: value.value,
              parentid: 0,
            };
            console.log("🚀 ~ .then ~ item:", item);
            const params = JSON.stringify(item);
            // this.$alert(params, {
            //   confirmButtonText: "确定",
            // });
            let result = window.iTag.updateTag(params);
            let res = JSON.parse(result);
            if (res.code == 1) {
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
            this.getAll();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消输入",
            });
          });
      },
      //添加子级标签
      append(data) {
        console.log("🚀 ~ append ~ data:", data);
        this.$prompt("", "请输入名称", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then((value) => {
            // console.log("🚀 ~ .then ~ value:", value.value);
            let item = {
              name: value.value,
              parentid: data.id,
            };

            console.log("🚀 ~ .then ~ item:", item);
            const params = JSON.stringify(item);
            // this.$alert(params, {
            //   confirmButtonText: "确定",
            // });
            let result = window.iTag.updateTag(params);
            let res = JSON.parse(result);
            if (res.code == 1) {
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
            this.getAll();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消输入",
            });
          });
        // const newChild = { id: id++, name: "testtest", children: [] };
        // if (!data.children) {
        //   this.$set(data, "children", []);
        // }
        // data.children.push(newChild);
      },

      remove(node, data) {
        console.log("🚀 ~ remove ~ data:", data);
        this.$confirm("是否删除?", "", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            let result = window.iTag.deleteTag(data.id);
            let res = JSON.parse(result);
            if (res.code == 1) {
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
            this.getAll();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
        // const parent = node.parent;
        // const children = parent.data.children || parent.data;
        // const index = children.findIndex((d) => d.id === data.id);
        // children.splice(index, 1);
      },

      renderContent(h, { node, data, store }) {
        return (
          <span class="custom-tree-node">
            <span>{node.label}</span>
            <span>
              <el-button
                size="mini"
                type="text"
                on-click={() => this.append(data)}>
                Append
              </el-button>
              <el-button
                size="mini"
                type="text"
                on-click={() => this.remove(node, data)}>
                Delete
              </el-button>
            </span>
          </span>
        );
      },
    },
  };
</script>

<style scoped>
  .operator {
    width: 100%;
    height: 98%;
  }
  /* :deep .el-table__body,
  .el-table__footer,
  .el-table__header {
    width: 100% !important;
  } */
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 120px;
  }
</style>
